package com.xiaoxing.yunshu.mvp.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.xiaoxing.yunshu.R;
import com.xiaoxing.yunshu.di.component.DaggerQuanXianSheZhiComponent;
import com.xiaoxing.yunshu.di.module.QuanXianSheZhiModule;
import com.xiaoxing.yunshu.mvp.contract.QuanXianSheZhiContract;
import com.xiaoxing.yunshu.mvp.presenter.QuanXianSheZhiPresenter;
import com.xiaoxing.yunshu.mvp.ui.entity.QuanXianSheZhi;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.armscomponent.commonres.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;

import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ACTIVITY_QUAN_XIAN_SHE_ZHI)
public class QuanXianSheZhiActivity extends BaseActivity<QuanXianSheZhiPresenter> implements QuanXianSheZhiContract.View {


    @BindView(R.id.btn_dian_chi_kuai_su_she_zhi)
    Button btnDianChiKuaiSuSheZhi;
    @BindView(R.id.btn_hou_tai_yun_xing_quan_xian_she_zhi)
    Button btnHouTaiYunXingQuanXianSheZhi;
    private PowerManager powerManager = null;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerQuanXianSheZhiComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .quanXianSheZhiModule(new QuanXianSheZhiModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_quan_xian_she_zhi; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.activity_quan_xian_she_zhi));
        //getQuanXianSheZhiData();
        powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);

    }

    @Override
    public void getQuanXianSheZhiDataSuccess(QuanXianSheZhi entityData) {


    }

    private void getQuanXianSheZhiData() {
        HashMap<String, String> map = new HashMap<>();

        mPresenter.getQuanXianSheZhiData(map);
    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog(this);
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @OnClick({R.id.btn_dian_chi_kuai_su_she_zhi, R.id.btn_hou_tai_yun_xing_quan_xian_she_zhi})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_dian_chi_kuai_su_she_zhi:

                // 在Android 6.0及以上系统，若定制手机使用到doze模式，请求将应用添加到白名单。
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    String packageName = getPackageName();
                    boolean isIgnoring = powerManager.isIgnoringBatteryOptimizations(packageName);
                    if (!isIgnoring) {
                        Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                        intent.setData(Uri.parse("package:" + packageName));
                        try {
                            startActivity(intent);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    } else {
                        showMessage("此应用已设置电池优化白名单");
                    }
                }
                break;
            case R.id.btn_hou_tai_yun_xing_quan_xian_she_zhi:
                showQuanXianSheZhiDialog();
                break;
        }
    }

    private void showQuanXianSheZhiDialog() {
        new QMUIDialog.MessageDialogBuilder(this)
                .setTitle("权限设置，非常重要！！！")
                .setCanceledOnTouchOutside(false)
                .setMessage("请关闭自动管理，必须改为[手动管理]，允许自启动和后台活动，否则无法正常记录轨迹。如果没有开启后台运行权限，将可能导致记录异常、距离减少、轨迹无法记录等问题。")
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(0, "去设置", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        jumpStartInterface(QuanXianSheZhiActivity.this);
                        mSharedPreferencesHelper.putBoolean(BaseConstants.YUN_XING_QUAN_XIAN, true);

                        dialog.dismiss();
                    }
                })
                .create(com.qmuiteam.qmui.R.style.QMUI_Dialog).show();
    }

    /**
     * GoTo Open Self Setting Layout
     * <p>
     * Compatible Mainstream Models 兼容市面主流机型
     *
     * @param context
     */

    public static void jumpStartInterface(Context context) {

        Intent intent = new Intent();

        intent = new Intent(Settings.ACTION_SETTINGS);

        context.startActivity(intent);
//        try {
//
//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//
//            Log.e("HLQ_Struggle", "******************当前手机型号为：" + getMobileType());
//
//            ComponentName componentName = null;
//
//            if (getMobileType().equals("Xiaomi")) {// 红米Note4测试通过
//
//                componentName = new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity");
//
//            } else if (getMobileType().equals("Letv")) {// 乐视2测试通过
//
//                intent.setAction("com.letv.android.permissionautoboot");
//
//            } else if (getMobileType().equals("samsung")) {// 三星Note5测试通过
//
//                componentName = new ComponentName("com.samsung.android.sm_cn", "com.samsung.android.sm.ui.ram.AutoRunActivity");
//
//            } else if (getMobileType().equals("HUAWEI")) {// 华为测试通过
//
//                componentName = new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity");
//
//            } else if (getMobileType().equals("vivo")) {// VIVO测试通过
//
//                componentName = ComponentName.unflattenFromString("com.iqoo.secure/.safeguard.PurviewTabActivity");
//
//            } else if (getMobileType().equals("Meizu")) {//万恶的魅族
//
//// 通过测试，发现魅族是真恶心，也是够了，之前版本还能查看到关于设置自启动这一界面，系统更新之后，完全找不到了，心里默默Fuck！
//
//// 针对魅族，我们只能通过魅族内置手机管家去设置自启动，所以我在这里直接跳转到魅族内置手机管家界面，具体结果请看图
//
//                componentName = ComponentName.unflattenFromString("com.meizu.safe/.permission.PermissionMainActivity");
//
//            } else if (getMobileType().equals("OPPO")) {// OPPO R8205测试通过
//
//                componentName = ComponentName.unflattenFromString("com.oppo.safe/.permission.startup.StartupAppListActivity");
//
//            } else if (getMobileType().equals("ulong")) {// 360手机 未测试
//
//                componentName = new ComponentName("com.yulong.android.coolsafe", ".ui.activity.autorun.AutoRunListActivity");
//
//            } else {
//
//// 以上只是市面上主流机型，由于公司你懂的，所以很不容易才凑齐以上设备
//
//// 针对于其他设备，我们只能调整当前系统app查看详情界面
//
//// 在此根据用户手机当前版本跳转系统设置界面
//
//                if (Build.VERSION.SDK_INT >= 9) {
//
//                    intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
//
//                    intent.setData(Uri.fromParts("package", context.getPackageName(), null));
//
//                } else if (Build.VERSION.SDK_INT <= 8) {
//
//                    intent.setAction(Intent.ACTION_VIEW);
//
//                    intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
//
//                    intent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
//
//                }
//
//            }
//
//            intent.setComponent(componentName);
//
//            context.startActivity(intent);
//
//        } catch (Exception e) {//抛出异常就直接打开设置页面
//
//            intent = new Intent(Settings.ACTION_SETTINGS);
//
//            context.startActivity(intent);
//
//        }

    }

    private static String getMobileType() {

        return android.os.Build.BRAND;
    }
}
